<?php

class ArticleController extends BaseManageController{
	public function actionAdmin(){
		$this->pageTitle = '文章管理列表 - ' . Yii::app()->name;
		$mod = new ArticleModel();
		$con = array(
			'site_id' => SITE_ID
		);
		$total = $mod->count($con);
		$this->setPagination($total);
		$article_list = $mod->find($con, null, $this->pager->offset, $this->pager->pageSize);
		$this->render('admin', array('list'=>$article_list));
	}
	
	public function actionEdit($id = null, $cate = null){
		if(Yii::app()->request->isPostRequest){
			$this->_save();
		}
		$this->pageTitle = '文章编辑 - ' . Yii::app()->name;
		if($id == null){
			$article = array(
				'_id'			=> '',
				'cate'			=> $cate,
				'stock'			=> -1,
				'price'			=> 0.00,
				'tpl_view'		=> 'view',
				'name_view'		=> '{$id}.html',
				'seo_title'		=> '{$cate_name} - {$site_name}',
				'seo_keywords'	=> '{$cate_name},{$site_keywords}',
				'seo_descript'	=> '{$site_desc}',
				'rank'			=> 255,
				'assumer'		=> 'buyer',
			);
		}else{
			$mod = new ArticleModel();
			$article = $mod->get_by_key($id);
			if($article['site_id'] != SITE_ID){
				throw new CHttpException(403, '非法请求！');
			}
		}
		$this->render('edit', array('model'=>$article));
	}

	/**
	 * 保存文章
	 * @param string $id 文章ID
	 */
	private function _save(){
		if(!isset($_POST['Article'])){
			$this->ajax_error('非法请求！');
		}
		$article = $_POST['Article'];
		$mod = new ArticleModel();
		$article['rank'] = intval($article['rank']);
		if(empty($article['_id'])){
			$article_id = CommonHelper::gen_uuid();
		}else{
			$article_id = $article['_id'];
		}

		//处理图片
		$this->init_pictures('article/' . date('Y/m/d/'), $article);
		
		if(empty($article['_id'])){
			//新建
			$article['update_user_id'] = $article['create_user_id'] = intval(Yii::app()->user->id);
			$article['create_time'] = $article['update_time'] = time();
			$article['site_id'] = SITE_ID;
			$article['_id'] = $article_id;
			$mod->insert($article);
		}else{
			$article['update_time'] = time();
			$article['update_user_id'] = intval(Yii::app()->user->id);
			$mod->update_by_key($article['_id'], $article);
		}
		$this->ajax_info('保存成功！', $article_id);
	}
}